package com.anysoft.login;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.hardware.fingerprint.FingerprintManager;
import android.os.Build;
import android.os.Bundle;
import android.os.CancellationSignal;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.anysoft.HostConstant;
import com.anysoft.MentorConst;
import com.anysoft.R;
import com.anysoft.base.BaseActivity;
import com.anysoft.bean.AccountLoginBean;
import com.anysoft.bean.ResultBean;
import com.anysoft.bean.UserBean;
import com.anysoft.event.FundBannerLoginEvent;
import com.anysoft.event.HomeBannerLoginEvent;
import com.anysoft.user.UserManageListviewActivity;
import com.anysoft.utils.ActivityUtils;
import com.anysoft.utils.AnalyticsEventUtils;
import com.anysoft.utils.AnalyticsUtils;
import com.anysoft.utils.HttpUtils;
import com.anysoft.utils.ParamUtil;
import com.anysoft.utils.PreferencesUtils;
import com.anysoft.view.FingerPrinterView;
import com.anysoft.view.dialog.DialogUtils;
import com.anysoft.view.dialog.IcbcDialog;
import com.anysoft.web.SearchTradeNewActivity;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

import static com.anysoft.MentorConst.ACCOUNT_LOCKOUT;
import static com.anysoft.utils.BitmapUtils.getDiskBitmap;

/**
 * Created by wwq on 2017/1/4.
 */

@TargetApi(Build.VERSION_CODES.M)
public class LoginByFingerPrintActivity extends BaseActivity {

    @BindView(R.id.tv_login_other)
    TextView tvLoginOther;
    @BindView(R.id.tv_login_change)
    TextView tvLoginChange;
    @BindView(R.id.ll_bottom)
    LinearLayout llBottom;
    @BindView(R.id.civ_user_icon)
    CircleImageView civUserIcon;
    @BindView(R.id.tv_icon_login_username)
    TextView tvIconLoginUsername;
    @BindView(R.id.fpv)
    FingerPrinterView fingerPrinterView;
    @BindView(R.id.iv_finger)
    ImageView ivFinger;
    private int fingerErrorNum = 1; // 指纹错误次数

    private FingerprintManager manager;//访问指纹硬件的类
    private KeyguardManager keyManager;//管理锁屏的类
    private CancellationSignal signal;
    //此类基于Java加密API的一个包装类,用于防止在指纹扫描中被第三方恶意攻击
    private FingerprintManager.CryptoObject cryptoObject;
    private static final int REQUST_CODE = 1;
    private String minSdkVersion;

    private String userId = "";

    private IcbcDialog fingerPrintDialog;

    private IcbcDialog fialeIcbcDialog;

    private boolean isFirstComing = true;

    /**
     * 是否是来自指纹三次错误
     */
    private boolean isFromFaileThreeTimes = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_login_finger_print);
        ButterKnife.bind(this);

        userId = getIntent().getStringExtra("userId");

        UserBean userBean = findUser(userId);
        if (userBean != null) {
            String userName = userBean.getUserName();
            tvIconLoginUsername.setText(ParamUtil.formatUserName(userName));

            String pathUrl = userBean.getUserImgPath();
            if (!TextUtils.isEmpty(pathUrl)) {
                Logger.t("pathUrl").d(pathUrl);
                Bitmap bitmap = getDiskBitmap(pathUrl);
                if (bitmap != null) {
                    civUserIcon.setImageBitmap(bitmap);
                }
            } else {
                if ("0".equals(userBean.getSex())) {//女
                    civUserIcon.setImageResource(R.mipmap.icon_user_w);
                } else if ("1".equals(userBean.getSex())) {//男
                    civUserIcon.setImageResource(R.mipmap.icon_user_m);
                } else {
                    civUserIcon.setBackground(getResources().getDrawable(R.mipmap.icon_user));
                }
            }
        } else {
            civUserIcon.setBackground(getResources().getDrawable(R.mipmap.icon_user));
        }

//        fingerPrinterView.setOnStateChangedListener(new FingerPrinterView.OnStateChangedListener() {
//            @Override
//            public void onChange(int state) {
//                if (state == FingerPrinterView.STATE_CORRECT_PWD) {
//                    fingerErrorNum = 0;
//                    Toast.makeText(mActivity, "指纹识别成功", Toast.LENGTH_SHORT).show();
//                }
//                if (state == FingerPrinterView.STATE_WRONG_PWD) {
//                    Toast.makeText(mActivity, "指纹识别失败，请重试", Toast.LENGTH_SHORT).show();
//                    fingerErrorNum++;
//                    fingerPrinterView.setState(FingerPrinterView.STATE_NO_SCANING);
//                }
//            }
//        });

        minSdkVersion = Build.VERSION.SDK;
        if (Double.parseDouble(minSdkVersion) >= 23) {
            initFingerPrint();
        } else {
            initLowSDK();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void initFingerPrint() {
        initFinger();
        if (isFingerprint()) {
            startListen();
        }

        fingerPrintDialog = new IcbcDialog(this);
        fingerPrintDialog.setAnimationEnable(true);
        fingerPrintDialog.setCancelable(false);
        fingerPrintDialog.setTitle("指纹验证");
        fingerPrintDialog.setContentText("XXXXXX登录，请验证已有指纹");
        fingerPrintDialog.setContentImage(getResources().getDrawable(R.mipmap.finger_red));
        fingerPrintDialog.setPositiveListener("取消", new IcbcDialog.OnPositiveListener() {
            @Override
            public void onClick(IcbcDialog dialog) {
                dialog.dismiss();

                if (signal != null) {
                    signal.cancel();
                    signal = null;
                }
            }
        }).show();
    }

    private void initLowSDK() {
        fingerPrintDialog.dismiss();

        showConfirmAlert(mActivity, "温馨提示", "目前指纹识别只支持6.0以上的系统哦!");
    }

    /**
     * 获得系统服务对象的引用
     */
    private void initFinger() {
        //通过V4包获得对象
        manager = (FingerprintManager) getSystemService(Context.FINGERPRINT_SERVICE);
        keyManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
        signal = new CancellationSignal();

    }

    @TargetApi(Build.VERSION_CODES.M)
    private boolean isFingerprint() {
        //此方法为了保证判断是否支持支持指纹不报错
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(getBaseContext(), "没有指纹解锁的权限", Toast.LENGTH_SHORT).show();
            return false;
        }
        //硬件设备是否支持指纹解锁功能
        if (!manager.isHardwareDetected()) {
            Toast.makeText(getBaseContext(), "该手机不支持指纹解锁", Toast.LENGTH_SHORT).show();
            return false;
        }
        //判断是否有锁屏密码
        if (!keyManager.isKeyguardSecure()) {
            Toast.makeText(getBaseContext(), "请设置锁屏密码", Toast.LENGTH_SHORT).show();
            return false;
        }
        //判断是否录入指纹
        if (!manager.hasEnrolledFingerprints()) {
            Toast.makeText(getBaseContext(), "没有录入指纹", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    /**
     * 开始指纹识别
     */
    private void startListen() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
            return;
        }

//        fingerPrinterView.setState(FingerPrinterView.STATE_SCANING);

        FingerprintManager.AuthenticationCallback callBack = new FingerprintManager.AuthenticationCallback() {
            @Override
            public void onAuthenticationError(int errorCode, CharSequence errString) {
                super.onAuthenticationError(errorCode, errString);
                Logger.t("onAuthenticationError").d(errString.toString());

                if (isFirstComing) {
                    isFirstComing = false;
                } else {
                    if (!isFromFaileThreeTimes) {
                        if (fingerPrintDialog != null && fingerPrintDialog.isShowing()) {
                            fingerPrintDialog.dismiss();
                        }

                        if (fialeIcbcDialog != null && fialeIcbcDialog.isShowing()) {
                            fialeIcbcDialog.dismiss();
                        }

                        fialeIcbcDialog = new IcbcDialog(LoginByFingerPrintActivity.this);
                        fialeIcbcDialog.setAnimationEnable(true);
                        fialeIcbcDialog.setCancelable(false);
                        fialeIcbcDialog.setTitle("指纹验证");
                        fialeIcbcDialog.setContentText(errString.toString());
                        fialeIcbcDialog.setPositiveListener("确定", new IcbcDialog.OnPositiveListener() {
                            @Override
                            public void onClick(IcbcDialog dialog) {
                                dialog.dismiss();

                                if (signal != null) {
                                    signal.cancel();
                                    signal = null;
                                }
                            }
                        }).show();
                    } else {
                        isFromFaileThreeTimes = false;
                    }
                }
            }

            @Override
            public void onAuthenticationHelp(int helpCode, CharSequence helpString) {
                super.onAuthenticationHelp(helpCode, helpString);
                Logger.t("onAuthenticationHelp").d(helpString.toString());
            }

            //指纹识别成功
            @Override
            public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) {
                super.onAuthenticationSucceeded(result);
                Logger.t("onAuthenticationSucceeded").d("指纹验证成功");
//                Toast.makeText(mActivity, "指纹识别成功", Toast.LENGTH_SHORT).show();
//                fingerPrinterView.setState(FingerPrinterView.STATE_CORRECT_PWD);

                login();

            }

            //指纹识别失败
            @Override
            public void onAuthenticationFailed() {
                super.onAuthenticationFailed();
                if (fingerPrintDialog != null && fingerPrintDialog.isShowing()) {
                    fingerPrintDialog.dismiss();
                }

                if (fialeIcbcDialog != null && fialeIcbcDialog.isShowing()) {
                    fialeIcbcDialog.dismiss();
                }

                Toast.makeText(mActivity, "指纹识别失败", Toast.LENGTH_SHORT).show();
//                fingerPrinterView.setState(FingerPrinterView.STATE_WRONG_PWD);

                if (fingerErrorNum == MentorConst.GESTURE_OR_FINGERPRINT_FAIL_TIMES) {
                    isFromFaileThreeTimes = true;
                    if (signal != null) {
                        signal.cancel();
                        signal = null;
                    }
                    DialogUtils utils = new DialogUtils();
                    utils.contentAlert(mActivity, "提示", "您已连续输入指纹错误，请重新登录", "确定", "");
                    utils.setOnContentDialogSbtnListener(new DialogUtils.OnContentDialogSbtnListener() {
                        @Override
                        public void OnContentDialogSbtnClick() {
                            startActivity(new Intent().setClass(mActivity, LoginActivity.class));
                            finish();
                        }
                    });
                } else {
                    fingerPrintDialog = new IcbcDialog(mActivity);
                    fingerPrintDialog.setAnimationEnable(true);
                    fingerPrintDialog.setCancelable(false);
                    fingerPrintDialog.setTitle("再试一次");
                    fingerPrintDialog.setContentText("XXXXXX登录，请验证已有指纹");
                    fingerPrintDialog.setNegativeListener("其他登录方式", new IcbcDialog.OnNegativeListener() {
                        @Override
                        public void onClick(IcbcDialog dialog) {
                            dialog.dismiss();

                            loginWithOther();
                        }
                    });
                    fingerPrintDialog.setPositiveListener("取消", new IcbcDialog.OnPositiveListener() {
                        @Override
                        public void onClick(IcbcDialog dialog) {
                            dialog.dismiss();

                            if (signal != null) {
                                signal.cancel();
                                signal = null;
                            }
                        }
                    }).show();
                }
            }
        };
        manager.authenticate(cryptoObject, signal, 0, callBack, null);
    }


    private void login() {
        showLoading(mActivity);
        Map<String, String> params = new HashMap<>();

        params.put("identityNo", userId);
        params.put("identityType", getUserType(userId));
        params.put("fundCustomerNo", getCustomerNo(userId));
        params.put("loginState", "1");//开启或者修改的内容 	1指纹  2手势
        params.put("fingerprintKey", getLocalSecretKey(mActivity, userId));
        params.put("signKey", "");
        params.put("randomKey", getFingerPrintRandomKey(userId));
        params.put("mobileStyle", Build.MANUFACTURER);
        OkGo.<String>post(HostConstant.VALIDATE_SIGN_FINGER_PRINT_CONFIRM)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        UpdateJson(response.body());
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast("网络加载失败，请稍后再试!");
                        hideLoading();
                        HostConstant.SKIP_TYPE = "";
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    private void UpdateJson(String json) {
        hideLoading();
        AccountLoginBean bean = null;
        try {
            bean = new Gson().fromJson(json, AccountLoginBean.class);
        } catch (Exception exception) {
            exception.printStackTrace();
        }

        ResultBean resultBean = checkStateBean(bean, json);
        if (!resultBean.isSuccess()) {
            if ("-4032".equals(resultBean.getCode()) || "-4058".equals(resultBean.getCode())) {
                DialogUtils utils = new DialogUtils();
                utils.contentAlert(mActivity, "提示", resultBean.getTip(), "确定", "");
                utils.setOnContentDialogSbtnListener(new DialogUtils.OnContentDialogSbtnListener() {
                    @Override
                    public void OnContentDialogSbtnClick() {
//                        clearFingerPrint(userId);
//                        startActivity(new Intent().setClass(mActivity, LoginActivity.class));
                        clearUserPwd(userId);
                        Intent intent = new Intent().setClass(mActivity, UserIconLoginActivity.class);
                        intent.putExtra("userId", userId);
                        startActivity(intent);
                        finish();
                    }
                });
            } else if (ACCOUNT_LOCKOUT.equals(resultBean.getCode())) {
                if (fingerPrintDialog != null && fingerPrintDialog.isShowing()) {
                    fingerPrintDialog.dismiss();
                }

                if (fialeIcbcDialog != null && fialeIcbcDialog.isShowing()) {
                    fialeIcbcDialog.dismiss();
                }

                isFromFaileThreeTimes = true;
                if (signal != null) {
                    signal.cancel();
                    signal = null;
                }

                DialogUtils utils = new DialogUtils();
                utils.contentAlert(mActivity, "提示", resultBean.getTip(), "确定", "");
                utils.setOnContentDialogSbtnListener(new DialogUtils.OnContentDialogSbtnListener() {
                    @Override
                    public void OnContentDialogSbtnClick() {
                        finish();
                    }
                });
            } else {
                if (fingerPrintDialog != null && fingerPrintDialog.isShowing()) {
                    fingerPrintDialog.dismiss();
                }

                if (fialeIcbcDialog != null && fialeIcbcDialog.isShowing()) {
                    fialeIcbcDialog.dismiss();
                }

                isFromFaileThreeTimes = true;
                if (signal != null) {
                    signal.cancel();
                    signal = null;
                }

                DialogUtils utils = new DialogUtils();
                utils.contentAlert(mActivity, "提示", resultBean.getTip(), "确定", "");
                utils.setOnContentDialogSbtnListener(new DialogUtils.OnContentDialogSbtnListener() {
                    @Override
                    public void OnContentDialogSbtnClick() {
                        finish();
                    }
                });
            }
            HostConstant.SKIP_TYPE = "";
            return;
        }
        loginSuccess(bean);
    }

    private void loginSuccess(AccountLoginBean bean) {
        AnalyticsEventUtils.toLoginFingerEvent(this);
        AnalyticsUtils.onAnalyticsLogin(bean.getData().getIdentityNo());
        showToast("登录成功");
        PreferencesUtils.putBoolean(this, findUserId() + "CanGesture", true);
        UserBean userBean = new UserBean();
        userBean.setUserName(bean.getData().getRealName());
        userBean.setUserId(userId);
        userBean.setUserType(getUserType(userId));
        userBean.setToken(bean.getData().getToken());
        userBean.setFundCustomerNo(bean.getData().getFundCustomerNo());

        saveUser(userBean, bean);

        PreferencesUtils.putString(this, MentorConst.LAST_LOGIN_USER_ID, userId);
        if ("from_redeem".equals(HostConstant.SKIP_TYPE)) {
            ActivityUtils.gotoAssetsFundActivity(this);
        } else if ("from_salary".equals(HostConstant.SKIP_TYPE)) {
            ActivityUtils.gotoFixInvestmentAllActivity(this);
        } else if ("from_query".equals(HostConstant.SKIP_TYPE)) {
            startActivity(new Intent().setClass(this, SearchTradeNewActivity.class));
        } else if ("from_home_banner".equals(HostConstant.SKIP_TYPE)) {
            EventBus.getDefault().post(new HomeBannerLoginEvent(true));
        } else if ("from_fund_banner".equals(HostConstant.SKIP_TYPE)) {
            EventBus.getDefault().post(new FundBannerLoginEvent(true));
        }
        HostConstant.SKIP_TYPE = "";
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUST_CODE && resultCode == RESULT_OK) {
            Toast.makeText(getBaseContext(), "密码输入正确!", Toast.LENGTH_SHORT).show();
            finish();
        } else {
            Toast.makeText(getBaseContext(), "识别失败!", Toast.LENGTH_SHORT).show();
        }
    }

    private void loginWithOther() {
        Intent intent = new Intent();
        if (getGestureOpen(userId) && PreferencesUtils.getBoolean(this, userId + "CanGesture", true)) {
            intent.setClass(mActivity, LoginByGestureActivity.class);
            intent.putExtra("userId", userId);
            startActivity(intent);
            finish();
            return;
        }

        intent.setClass(mActivity, UserIconLoginActivity.class);
        intent.putExtra(MentorConst.IS_FROM_GESTURE, false);
        intent.putExtra("userId", userId);
        startActivity(intent);
        finish();
    }

    @OnClick({R.id.tv_login_other, R.id.tv_login_change, R.id.fpv, R.id.iv_finger})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_login_other:
                loginWithOther();
                break;
            case R.id.tv_login_change:
                startActivity(new Intent().setClass(mActivity, UserManageListviewActivity.class));
                finish();
                break;
            case R.id.iv_finger:
                initFingerPrint();
                break;
            case R.id.fpv:
//                initFingerPrint();
                break;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        dismissDialog();
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            HostConstant.SKIP_TYPE = "";
            finish();
        }
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dismissDialog();
    }

    private void dismissDialog() {
        if (fingerPrintDialog != null && fingerPrintDialog.isShowing()) {
            fingerPrintDialog.dismiss();
        }
        if (fialeIcbcDialog != null && fialeIcbcDialog.isShowing()) {
            fialeIcbcDialog.dismiss();
        }
    }
}
